//@version=6
indicator("INMERELO EMA Reclaim", overlay=true, max_labels_count=500)

// ===========================
// User Inputs
// ===========================
emaLen        = input.int(6, "Intraday EMA Length")
emaTF         = input.timeframe("", "EMA Timeframe (empty = chart TF)")

macdFast      = input.int(6, "MACD Fast Length")
macdSlow      = input.int(20, "MACD Slow Length")
macdSignal    = input.int(9, "MACD Signal Smoothing")

lowerQuantile = input.float(0.40, "Open ≤ position in range (0–1)", minval=0, maxval=1)
upperQuantile = input.float(0.70, "Close ≥ position in range (0–1)", minval=0, maxval=1)
minBodyFrac   = input.float(0.50, "Body ≥ fraction of range (0–1)",  minval=0, maxval=1)

minClosesBelow = input.int(2, "Minimum prior closes below EMA", minval=1, maxval=10)

paintCandle   = input.bool(true, "Paint INMERELO Candle?")
candleColor   = input.color(color.new(color.lime,0), "Candle Color")
showArrow     = input.bool(false, "Show Arrow?")  // default off
arrowSizeInp  = input.string("normal", "Arrow size", options=["tiny","small","normal","large"])

// ===========================
// EMA Calculation
// ===========================
emaVal = emaTF == "" ? ta.ema(close, emaLen) : request.security(syminfo.tickerid, emaTF, ta.ema(close, emaLen))

// ===========================
// MACD Calculation
// ===========================
[macdLine, macdSignalLine, _] = ta.macd(close, macdFast, macdSlow, macdSignal)
macdCondition = macdLine > macdSignalLine

// ===========================
// Candle geometry filters
// ===========================
rng  = high - low
body = math.abs(close - open)

openPos  = rng > 0 ? (open  - low) / rng : na
closePos = rng > 0 ? (close - low) / rng : na

openOK  = not na(openPos)  and openPos  <= lowerQuantile
closeOK = not na(closePos) and closePos >= upperQuantile
bodyOK  = rng > 0 and body / rng >= minBodyFrac

// ===========================
// Detect EMA reclaim with configurable prior closes below EMA
// ===========================
priorBelow = true
for i = 1 to minClosesBelow
    priorBelow := priorBelow and close[i] < emaVal[i]

inmereCondition = priorBelow and close > emaVal and macdCondition and openOK and closeOK and bodyOK

// ===========================
// Paint candle
// ===========================
barcolor(paintCandle and inmereCondition ? candleColor : na)

// ===========================
// Optional Arrow
// ===========================
arrowSize = arrowSizeInp=="tiny" ? size.tiny : arrowSizeInp=="small" ? size.small : arrowSizeInp=="normal" ? size.normal : size.large
if showArrow and inmereCondition
    label.new(bar_index, high, "↑", color=candleColor, style=label.style_label_up, size=arrowSize, yloc=yloc.abovebar)
